<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input id="filterName" v-model="search" placeholder="Filter by 员工姓名" style="width: 400px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 20px" @click="handleFilter">
        Search
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        Add
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="员工工号" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.staffId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="员工姓名" min-width="50px">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.staffName }}</span>
          <!--          <el-tag>{{ row.staffName | typeFilter }}</el-tag>-->
        </template>
      </el-table-column>
      <el-table-column label="起始时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.startTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.endTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假类型" align="center" width="95">
        <template slot-scope="{row}">
          <span v-if="row.type" class="link-type">{{ row.type }}</span>
          <span v-else>0</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.state">
            {{ row.state }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!--新增信息弹窗 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" style="width: 1700px;">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="120px" style="width: 100%; margin-left:30px; height: 350px;">
        <el-col span="10">
          <el-form-item label="员工工号">
            <el-input v-model="temp.staffId" />
          </el-form-item>
          <el-form-item label="员工姓名">
            <el-input v-model="temp.staffName" />
          </el-form-item>
          <el-form-item label="所属部门">
            <el-input v-model="temp.department" />
          </el-form-item>
          <el-form-item label="请假起始时间">
            <el-date-picker v-model="temp.startTime" type="datetime" placeholder="Please pick a date" />
          </el-form-item>
          <el-form-item label="请假结束时间">
            <el-date-picker v-model="temp.endTime" type="datetime" placeholder="Please pick a date" />
          </el-form-item>
          <el-form-item label="请假类型">
            <el-select v-model="temp.type" class="filter-item" placeholder="Please select" @change="typeChange">
              <el-option v-for="item in typeOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col span="10" style="margin-left: 50px;">
          <el-form-item label="请假事由">
            <el-input v-model="temp.reason" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="temp.staffTel" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="temp.staffMail" />
          </el-form-item>
          <el-form-item label="审核结果">
            <el-select v-model="temp.state" class="filter-item" placeholder="Please select" @change="selectChanged">
              <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-footer>
            <el-button @click="dialogFormVisible = false">
              取消
            </el-button>
            <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
              确认
            </el-button>
          </el-footer>
        </el-col>
      </el-form>
    </el-dialog>
    <!--详情弹窗 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" style="width: 1700px;">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 100%; margin-left:30px; height: 350px;">
        <el-col span="10">
          <el-form-item label="员工工号" prop="type">
            <el-input v-model="temp.staffId" />
          </el-form-item>
          <el-form-item label="员工姓名" prop="type">
            <el-input v-model="temp.staffName" />
          </el-form-item>
          <el-form-item label="所属部门" prop="type">
            <el-input v-model="temp.department" />
          </el-form-item>
          <el-form-item label="请假起始时间" prop="timestamp">
            <el-date-picker v-model="temp.startTime" type="datetime" placeholder="Please pick a date" />
          </el-form-item>
          <el-form-item label="请假结束时间" prop="timestamp">
            <el-date-picker v-model="temp.endTime" type="datetime" placeholder="Please pick a date" />
          </el-form-item>
          <el-form-item label="请假类型">
            <el-select v-model="temp.type" class="filter-item" placeholder="Please select">
              <el-option v-for="item in typeOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col span="10" style="margin-left: 50px;">
          <el-form-item label="请假事由">
            <el-input v-model="temp.reason" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
          </el-form-item>
          <el-form-item label="联系电话" prop="title">
            <el-input v-model="temp.staffTel" />
          </el-form-item>
          <el-form-item label="邮箱" prop="title">
            <el-input v-model="temp.staffMail" />
          </el-form-item>
          <el-form-item label="审核结果">
            <el-select v-model="temp.state" class="filter-item" placeholder="Please select" @change="selectChanged">
              <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-footer>
            <el-button @click="dialogFormVisible = false">
              取消
            </el-button>
            <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
              确认
            </el-button>
          </el-footer>
        </el-col>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, fetchPv, createArticle, updateArticle } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        isSpecial: true,
        sort: '+id'
      },
      search: '',
      searchList: [],
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['未审核', '通过', '退回'],
      typeOptions: ['事假', '病假', '产假', '婚假'],
      showReviewer: false,
      temp: {
        id: undefined,
        staffId: undefined,
        staffName: '',
        department: '',
        reason: '',
        startTime: new Date(),
        endTime: new Date(),
        staffTel: '',
        staffMail: '',
        type: '',
        state: '未审核'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改请假信息',
        create: '登记请假信息'
      },
      dialogPvVisible: false,
      pvData: [],
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      // this.listQuery.page = 1
      // this.getList()
      return this.list.filter(value => {
        console.log(value.staffName)
        // return value.staffName.match(this.search)
        if (value.staffName.match(this.search) != null) {
          this.searchList.push(value)
          console.log(value)
        }
        this.list = this.searchList
      })
    },
    handleModifyStatus(row, state) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.state = state
      const tempData = Object.assign({}, row)
      updateArticle(tempData).then(() => {
        const index = this.list.findIndex(v => v.id === row.id)
        this.list.splice(index, 1, row)
        this.$notify({
          title: 'Success',
          message: 'Update Successfully',
          type: 'success',
          duration: 2000
        })
      })
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          createArticle(this.temp).then(() => {
            var end = this.temp.endTime.getTime()
            var start = this.temp.startTime.getTime()
            // 时间差 = 结束时间 - 开始时间，这样得到的差值是毫秒级别
            var timeLag = end - start
            // 天
            var day = timeLag / (24 * 60 * 60 * 1000)
            if (day > 30) {
              this.temp.state = '未审核'
              this.temp.isSpecial = true
            }
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    typeChange(value) {
      console.log(value)
      this.temp.type = value
    },
    selectChanged(value) {
      console.log(value)
      this.temp.state = value
    },
    updateData() {
      const tempData = Object.assign({}, this.temp)
      updateArticle(tempData).then(() => {
        const index = this.list.findIndex(v => v.id === this.temp.id)
        this.list.splice(index, 1, this.temp)
        this.dialogFormVisible = false
        this.$notify({
          title: 'Success',
          message: 'Update Successfully',
          type: 'success',
          duration: 2000
        })
      })
    },
    // updateData() {
    //   this.$refs['dataForm'].validate((valid) => {
    //     if (valid) {
    //       const tempData = Object.assign({}, this.temp)
    //       tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
    //       updateArticle(tempData).then(() => {
    //         const index = this.list.findIndex(v => v.id === this.temp.id)
    //         this.list.splice(index, 1, this.temp)
    //         this.dialogFormVisible = false
    //         this.$notify({
    //           title: 'Success',
    //           message: 'Update Successfully',
    //           type: 'success',
    //           duration: 2000
    //         })
    //       })
    //     }
    //   })
    // },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
